//
//  JHBookDownLoadView.m
//  JuniRengLish_iOS
//
//  Created by revogi on 2019/5/11.
//  Copyright © 2019 revogi. All rights reserved.
//

#import "JHBookDownLoadView.h"

@implementation JHBookDownLoadView


// 步骤 1：重写initWithFrame:方法，创建子控件并 - 添加
- (instancetype)initWithFrame:(CGRect)frame {
    
    self = [super initWithFrame:frame];
    if (self) {
        self.downLoadBtn.layer.cornerRadius =23;
        self.downLoadBtn.layer.masksToBounds = YES;
        self.downLoadBtn.layer.borderColor = [UIColor lightGrayColor].CGColor;
        [self.downLoadBtn.layer setBorderWidth:3];//边框宽度
    }
    return self;
}

- (void)setBookDetailModel:(JHBookDetailModel *)bookDetailModel
{
    _bookDetailModel = bookDetailModel;
    
    if ([self isAllBookExistFile])
    {
        [self.downLoadBtn setTitle:@"下载已完成" forState:UIControlStateNormal];
        self.downLoadBtn.enabled = NO;
    }
    else
    {
        [self.downLoadBtn setTitle:@"一键下载" forState:UIControlStateNormal];
        self.downLoadBtn.enabled = YES;
    }
}

//判断是否下载全部课文的mp3和txt文件
- (BOOL)isAllBookExistFile
{
    NSInteger count = 0;
    CGFloat totalCount = 0;
    
    if (self.isBook)
    {
        for (int i = 0; i < self.bookDetailModel.bookitem.count; i ++)
        {
            JHBookItemModel * model = self.bookDetailModel.bookitem[i];
            for (int j = 0; j < model.data.count; j ++)
            {
                totalCount ++;
            }
        }
        
        for (int i = 0; i < self.bookDetailModel.bookitem.count; i ++)
        {
            JHBookItemModel * model = self.bookDetailModel.bookitem[i];
            for (int j = 0; j < model.data.count; j ++)
            {
                JHBookItemDataModel * dataModel = model.data[j];
                NSString * txtFile = [[JHFileManger getDocumentsPath] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@", self.bookDetailModel.bookinfo.bookid, dataModel.textfile]];
                NSString * mp3File = [[JHFileManger getDocumentsPath] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@.mp3", self.bookDetailModel.bookinfo.bookid, dataModel.mp3name]];
                if ([JHFileManger fileExistsAtPath:txtFile] && [JHFileManger fileExistsAtPath:mp3File])
                {
                    count ++;
                }
            }
            
        }
    }
    else
    {
        for (int i = 0; i < self.bookDetailModel.worditem.count; i ++)
        {
            JHWordItemModel * model = self.bookDetailModel.worditem[i];
            for (int j = 0; j < model.data.count; j ++)
            {
                totalCount ++;
            }
        }
        
        for (int i = 0; i < self.bookDetailModel.worditem.count; i ++)
        {
            JHWordItemModel * model = self.bookDetailModel.worditem[i];
            for (int j = 0; j < model.data.count; j ++)
            {
                JHWordItemDataModeel * dataModel = model.data[j];
                NSString * txtFile = [[JHFileManger getDocumentsPath] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@", self.bookDetailModel.bookinfo.bookid, dataModel.textfile]];
                NSString * mp3File = [[JHFileManger getDocumentsPath] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@.mp3", self.bookDetailModel.bookinfo.bookid, dataModel.mp3name]];
                if ([JHFileManger fileExistsAtPath:txtFile] && [JHFileManger fileExistsAtPath:mp3File])
                {
                    count ++;
                }
            }
        }
    }
    
    if (count == totalCount)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

- (IBAction)downLoadBtnDidClik:(UIButton *)sender {
    
    [self.currentVC jxt_showAlertWithTitle:@"温馨提示" message:@"是否一键下载全部文件" appearanceProcess:^(JXTAlertController * _Nonnull alertMaker) {
        alertMaker.addActionCancelTitle(@"取消").addActionDefaultTitle(@"确定");
    } actionsBlock:^(NSInteger buttonIndex, UIAlertAction * _Nonnull action, JXTAlertController * _Nonnull alertSelf) {
        if (buttonIndex == 1) {
            [self downLoadZipFile];
        }
    }];
}

- (void)downLoadZipFile
{
    //反馈状态(正在下载)
    self.downLoadBtnBlock(YES);
    self.downLoadBtn.enabled = NO;
    
    NSString * doc = [[JHFileManger getDocumentsPath] stringByAppendingPathComponent:self.bookDetailModel.bookinfo.bookid];
    if ([JHFileManger fileExistsAtPath:doc])
    {
        NSLog(@"已经下载zip文件");
        
        if ([self isAllBookExistFile])
        {
            NSLog(@"已经下载mp3和txt");
        }
        else
        {
            self.isBook ? [self downBookAllMp3File] : [self downWordAllMp3File];
        }
    }
    else
    {
        //创建文件夹
        [JHFileManger createDirectory:doc];
        NSString *urlStr = [self.bookDetailModel.bookinfo.txtdownloadurl substringToIndex:self.bookDetailModel.bookinfo.txtdownloadurl.length-1];
        NSLog(@"%@ ==  下载的地址",urlStr);
        
        [DJHttpTool downloadURL:@{@"url":urlStr, @"fileName":self.bookDetailModel.bookinfo.bookid} progress:^(NSProgress *downloadProgress) {
            //更新下载进度
            NSLog(@"%@----hah ---", downloadProgress);
            
        } destination:^(NSURL *targetPath) {
            NSLog(@"targetPath : %@", [targetPath path]);
            //解压文件
            ([SSZipArchive unzipFileAtPath:[targetPath path] toDestination:doc]) ? (NSLog(@"解压完成")) : (NSLog(@"解压失败"));
            
            //下载所有的mp3文件
            self.isBook ? [self downBookAllMp3File] : [self downWordAllMp3File];
        } failure:^(NSError *error) {
            
        }];
        NSLog(@"  一键下载");
    }
}

#pragma mark - 下载所有的
- (void)downBookAllMp3File
{
    __block CGFloat count = 0;
    CGFloat totalCount = 0;
    for (int i = 0; i < self.bookDetailModel.bookitem.count; i ++)
    {
        JHBookItemModel * model = self.bookDetailModel.bookitem[i];
        for (int j = 0; j < model.data.count; j ++)
        {
            totalCount ++;
        }
    }
    WEAKSELF
    for (int i = 0; i < self.bookDetailModel.bookitem.count; i ++)
    {
        JHBookItemModel * model = self.bookDetailModel.bookitem[i];
        for (int j = 0; j < model.data.count; j ++)
        {
            JHBookItemDataModel * dataModel = model.data[j];
            NSString *urlStr = [dataModel.mp3url1 substringToIndex:dataModel.mp3url1.length-1];
            
            [DJHttpTool downloadURL:@{@"url":[urlStr stringByAppendingPathComponent:dataModel.mp3name], @"fileName":self.bookDetailModel.bookinfo.bookid, @"name":[dataModel.mp3name stringByAppendingString:@".mp3"]} progress:^(NSProgress *downloadProgress) {
                //更新下载进度
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                });
                NSLog(@"%@----hah ---", downloadProgress);
                
            } destination:^(NSURL *targetPath) {
                NSLog(@"targetPath : %@", [targetPath path]);
                dispatch_async(dispatch_get_main_queue(), ^{
                    count ++;
                    if (count == totalCount)
                    {
                        [weakSelf.downLoadBtn setTitle:@"下载已完成" forState:UIControlStateNormal];
                        
                        if (weakSelf.downLoadBtnBlock) {
                            weakSelf.downLoadBtnBlock(NO);
                        }
                    }
                    else
                    {
                        CGFloat percent = count / totalCount;
                        [weakSelf.downLoadBtn setTitle:[NSString stringWithFormat:@"下载中...(%.2f%%)", percent * 100] forState:UIControlStateNormal];
                    }
                });
            } failure:^(NSError *error) {
                
            }];
        }
    }
}

- (void)downWordAllMp3File
{
    __block CGFloat count = 0;
    CGFloat totalCount = 0;
    for (int i = 0; i < self.bookDetailModel.worditem.count; i ++)
    {
        JHWordItemModel * model = self.bookDetailModel.worditem[i];
        for (int j = 0; j < model.data.count; j ++)
        {
            totalCount ++;
        }
    }
    WEAKSELF
    for (int i = 0; i < self.bookDetailModel.worditem.count; i ++)
    {
        JHWordItemModel * model = self.bookDetailModel.worditem[i];
        for (int j = 0; j < model.data.count; j ++)
        {
            JHWordItemDataModeel * dataModel = model.data[j];
            NSString *urlStr = [dataModel.mp3url1 substringToIndex:dataModel.mp3url1.length-1];
            
            [DJHttpTool downloadURL:@{@"url":[urlStr stringByAppendingPathComponent:dataModel.mp3name], @"fileName":self.bookDetailModel.bookinfo.bookid, @"name":[dataModel.mp3name stringByAppendingString:@".mp3"]} progress:^(NSProgress *downloadProgress) {
                //更新下载进度
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                });
                NSLog(@"%@----hah ---", downloadProgress);
                
            } destination:^(NSURL *targetPath) {
                NSLog(@"targetPath : %@", [targetPath path]);
                dispatch_async(dispatch_get_main_queue(), ^{
                    count ++;
                    if (count == totalCount)
                    {
                        [weakSelf.downLoadBtn setTitle:@"下载已完成" forState:UIControlStateNormal];
                        
                        if (weakSelf.downLoadBtnBlock) {
                            weakSelf.downLoadBtnBlock(NO);
                        }
                    }
                    else
                    {
                        CGFloat percent = count / totalCount;
                        [weakSelf.downLoadBtn setTitle:[NSString stringWithFormat:@"下载中...(%.2f%%)", percent * 100] forState:UIControlStateNormal];
                    }
                });
            } failure:^(NSError *error) {
                
            }];
        }
    }
}


@end
